<?php

namespace system\model;

use houdunwang\model\Model;
use houdunwang\validate\Validate;
class Admin extends Model
{
	//操作的数据表
	protected $table = "admin";

	//登录
	public function login()
	{
		/*//1.验证数据不能为空
		$res = Validate::make( [
			//字段、验证规则、提示消息、验证条件,
				[ 'admin_username', 'isnull', '用户名不能为空', self::MUST_VALIDATE ],
				[ 'admin_password', 'isnull', '密码不能为空', self::MUST_VALIDATE ],
				[ 'code', 'isnull', '验证码不能为空', self::MUST_VALIDATE ]
		] );
		if($res===false){
			return ['valid'=>0,'msg'=>Validate::getError()];
			print_r(Validate::getError());
		}*/
		//1.验证数据不能为空
		$data = [
				'admin_username'=>q('post.admin_username'),
				'admin_password'=>q('post.admin_password'),
				'code'=>q('post.code'),
		];
		//p($data);die;
		$res = Validate::make( [
				[ 'admin_username', 'isnull', '请输入用户名', 3 ],
				[ 'admin_password', 'isnull', '请输入密码', 3 ],
				[ 'code', 'isnull', '请输入验证码', 3 ],
		] ,$data);
		//2.比对用户名密码是否正确
		//比对数据库与用户的用户名是否一致
		$userInfo = $this->where('admin_username',$data['admin_username'])->first();
		//不一致时进入判断，返回用户名不正确
		if(!$userInfo){
			return ['valid'=>0,'msg'=>'用户名不正确'];
		}
		//校验密码
		//比对数据库与用户的密码是否一致
		if(!password_verify($data['admin_password'],$userInfo['admin_password']))
		{
			//不一致时进入判断，返回密码不正确
			return ['valid'=>0,'msg'=>'用户密码不正确'];
		}


//			$userInfo = $this->where('admin_username',$data['admin_username'])
//				->where('admin_password',password_hash($data['admin_password'],PASSWORD_DEFAULT))
//				->first();
//			if(!$userInfo){
//				return ['valid'=>0,'msg'=>'用户名或者密码不正确'];
//			}
		//3.比对验证码是否正确
		//var_dump(Code::auth( 'code' ));die;
		if(!Code::auth( 'code' ))
		{
			return ['valid'=>0,'msg'=>'验证码不正确'];
		}
		//4.将当前登录用户信息存入session
		Session::set('admin.admin_id',$userInfo['admin_id']);
		Session::set('admin.admin_username',$userInfo['admin_username']);
		//5.返回成功
		return ['valid'=>1,'msg'=>'登录成功'];

	}
	/**
	 * 修改密码
	 */
	public function changePassword($data)
	{
		//dd($data);
		Validate::make([
				['admin_password','required','请输入原始密码',Validate::MUST_VALIDATE],
				['new_password','required','请输入新密码',Validate::MUST_VALIDATE],
			//比对确认密码跟新密码是否一致
				['retry_password','confirm:new_password','确认密码跟新密码不一致',Validate::MUST_VALIDATE],
		]);
		//比对原始密码是否正确
		$userInfo = self::find(Session::get('admin.admin_id'));
		if(!password_verify($data['admin_password'],$userInfo['admin_password'])){
			return ['valid'=>0,'message'=>'原始密码不正确'];
		}
		//走到这里说明原始密码是正确的，并且新密码和确认密码也没有问题
		$userInfo->admin_password = password_hash($data['new_password'],PASSWORD_DEFAULT);
		$userInfo->save();
		return ['valid'=>1,'message'=>'修改成功'];
	}
}
